<template>
    <div class="container">
        <!-- 控制栏容器 -->
        <el-form inline class="control-bar">
            <el-form-item label="Level">
                <el-select v-model="selectedLevel" placeholder="请选择层级" style="width: 150px">
                    <el-option v-for="level in levels" :key="level" :label="`${level} hPa`" :value="level" />
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="loadWindData">应用</el-button>
            </el-form-item>
        </el-form>

        <!-- 图表展示区域 -->
        <div class="chart-container">
            <el-skeleton :loading="loading" animated class="chart-skeleton">
                <template #template>
                    <el-skeleton-item variant="text" />
                    <el-skeleton-item variant="p" rows="6" />
                </template>
                <template #default>
                    <v-chart v-if="!error" class="chart" :option="option" autoresize />
                </template>
            </el-skeleton>
            <el-alert v-if="error" :title="`数据加载失败: ${error}`" type="error" show-icon class="error-alert" />
        </div>
    </div>
</template>

<script>
import { ref, onMounted } from 'vue';
import { use } from 'echarts/core';
import { CanvasRenderer } from 'echarts/renderers';
import { CustomChart } from 'echarts/charts';
import { VisualMapComponent, GeoComponent } from 'echarts/components';
import VChart from 'vue-echarts';
import worldData from '/src/world.json';

use([CanvasRenderer, CustomChart, VisualMapComponent, GeoComponent]);

import * as echarts from 'echarts';
echarts.registerMap('world', worldData);

function shuffle(array) {
    let currentIndex = array.length;
    while (currentIndex) {
        const randomIndex = Math.floor(Math.random() * currentIndex);
        currentIndex--;
        [array[currentIndex], array[randomIndex]] = [array[randomIndex], array[currentIndex]];
    }
    return array;
}

export default {
    components: { VChart },
    setup() {
        const option = ref(null);
        const loading = ref(true);
        const error = ref(null);
        const selectedLevel = ref(500);
        const levels = ref([]);

        const processData = (windData) => {
            let maxMag = -Infinity;
            let minMag = Infinity;
            const points = windData.Values;

            points.forEach(point => {
                const mag = point[4];
                maxMag = Math.max(mag, maxMag);
                minMag = Math.min(mag, minMag);
            });

            shuffle(points);

            option.value = {
                backgroundColor: '#333',
                visualMap: {
                    left: 'center',
                    min: minMag,
                    max: maxMag,
                    dimension: 4,
                    inRange: {
                        color: [
                            '#313695',
                            '#4575b4',
                            '#74add1',
                            '#abd9e9',
                            '#e0f3f8',
                            '#ffffbf',
                            '#fee090',
                            '#fdae61',
                            '#f46d43',
                            '#d73027',
                            '#a50026',
                        ],
                    },
                    calculable: true,
                    textStyle: {
                        color: '#fff',
                    },
                    orient: 'horizontal',
                },
                geo: {
                    map: 'world',
                    silent: true,
                    roam: true,
                    itemStyle: {
                        areaColor: '#323c48',
                        borderColor: '#111',
                    },
                },
                series: {
                    type: 'custom',
                    coordinateSystem: 'geo',
                    data: points,
                    encode: { x: 0, y: 0 },
                    renderItem: (params, api) => {
                        const x = api.value(0);
                        const y = api.value(1);
                        const dx = api.value(2);
                        const dy = api.value(3);
                        const start = api.coord([
                            Math.max(x - dx / 5, -180),
                            Math.max(y - dy / 5, -90),
                        ]);
                        const end = api.coord([
                            Math.min(x + dx / 5, 180),
                            Math.min(y + dy / 5, 90),
                        ]);
                        return {
                            type: 'line',
                            shape: { x1: start[0], y1: start[1], x2: end[0], y2: end[1] },
                            style: {
                                lineWidth: 0.5,
                                stroke: api.visual('color'),
                            },
                        };
                    },
                    progressive: 2000,
                },
            };
        };

        const loadLevels = async () => {
            try {
                const response = await fetch('/data/asset/Wind.json');
                if (!response.ok) throw new Error(`请求失败，状态码：${response.status}`);
                const data = await response.json();

                const rawLevels = data.levels || data.Levels || data["Level"] || [];
                levels.value = rawLevels.filter(Number.isInteger).sort((a, b) => a - b);

                const targetLevel = levels.value.find(l => l === 150);
                selectedLevel.value = targetLevel || (levels.value.length > 0 ? levels.value[0] : null);

                if (!targetLevel && levels.value.length > 0) {
                    console.warn('150 hPa数据不可用，使用默认层级:', selectedLevel.value);
                }
            } catch (err) {
                error.value = `层级加载失败: ${err.message}`;
            }
        };

        const loadWindData = async () => {
            try {
                loading.value = true;
                error.value = null;

                if (!selectedLevel.value) {
                    throw new Error('请选择有效层级');
                }

                const fileName = `/data/asset/Wind/Wind ${selectedLevel.value} hPa.json`;
                // const fileName = `/data/asset/Wind/Wind 150 hPa.json`;
                const response = await fetch(`${fileName}`);
                if (!response.ok) throw new Error(`请求失败，状态码：${response.status}`);

                const windData = await response.json();
                processData(windData);
            } catch (err) {
                error.value = `数据加载失败: ${err.message}`;
                console.error('请求错误:', err);
            } finally {
                loading.value = false;
            }
        };

        onMounted(async () => {
            await loadLevels();
            if (selectedLevel.value !== null && !error.value) {
                await loadWindData();
            } else {
                loading.value = false;
                error.value = error.value || '请先选择有效层级';
            }
        });

        return {
            option,
            loading,
            error,
            selectedLevel,
            levels,
            loadWindData
        };
    },
};
</script>

<style scoped>
.container {
    position: relative;
    height: 100vh;
    width: 100%;
    background: var(--el-background-color-page);
}

.control-bar {
    position: absolute;
    top: 10px;
    left: 20px;
    z-index: 1000;
    padding: 12px;
    background: var(--el-background-color-panel);
    box-shadow: var(--el-box-shadow-4);
    border-radius: var(--el-border-radius-base);
}

.chart-container {
    position: absolute;
    top: 60px;
    left: 0;
    right: 0;
    bottom: 0;
}

.chart-skeleton {
    height: 100%;
    width: 100%;
}

.chart {
    height: 100%;
    width: 100%;
}

.error-alert {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    width: 300px;
}
</style>